import axios from "axios";
import { ElMessage, ElNotification, ElMessageBox } from "element-plus";
import type {loginRes} from "@/types/index"
const requestUrl = "https://meituan.thexxdd.cn/cha";
export const uploadFileUrl = requestUrl + "/file/uploadfile";
import { Base64 } from "js-base64";
function encryptToken() {
  const { userToken } = JSON.parse(localStorage.getItem("userInfo") as string) as loginRes;
  const auth = Base64.encode(userToken + ":");
  return "Basic " + auth;
}


const axiosInstance = axios.create({
    baseURL:'https://meituan.thexxdd.cn/cha'
})

axiosInstance.interceptors.request.use(
    (config)=>{
      const userInfo = localStorage.getItem("userInfo")
      if(userInfo){
        config.headers.Authorization = encryptToken();
      }
        return config
    },
    (error)=>{
        return Promise.reject(error)
    }
)

axiosInstance.interceptors.response.use(
    (response)=>{
        return response.data
    },
    (error)=>{
        console.log(error);
        const status: number = error.response.status;
        const code: number = error.response.data.code;
    switch (status) {
      case 404:
        console.error("接口不存在或者请求方式不对");
        break;
      case 401:
        console.error("没有权限访问");
        if (code === 4001) {
          // 没有操作权限
          ElNotification({
            title: "提示",
            message: "你没有操作权限",
            type: "warning",
            duration: 2000,
          });
        } else {
          ElMessageBox.confirm(error.response.data.msg, "提示", {
            confirmButtonText: "我知道了",
            type: "warning",
            showCancelButton: false,
            showClose: false,
            closeOnClickModal: false,
            closeOnPressEscape: false,
          }).then(() => {
            window.location.href = "https://meituan.thexxdd.cn/chapc/#/";
          });
        }
        break;
        break;
      case 500:
      case 501:
      case 502:
        ElMessage({ message: "发生异常错误", duration: 1500 });
        break;
      case 400:
        ElMessage({ message: error.response.data.msg, duration: 1500 });
        break;
      case 422:
        ElMessage({ message: error.response.data.msg, duration: 1500 });
        break;
    }
    return Promise.reject(error);
  }
    
)
interface ApiResponse<T>{
    data:T
    msg:string
    error:any
    code:number
}

//get请求
export const get = <T>(url:string,params?:object):Promise<ApiResponse<T>>=>{
    return axiosInstance.get(url,{params})
};
export const post = <T>(url: string, data?: object): Promise<ApiResponse<T>> => {
  return axiosInstance.post(url, data);
}; 
//post请求